﻿package ui.container {
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.geom.Rectangle;
	import flash.events.Event;
	
	public class ScrollContainer extends Sprite
	{
		private var measureHeight: Number = 0.0;
		private var measureWidth: Number = 0.0;
		private var _verticalPosition: Number;
		private var _horizontalPosition: Number;
		
		
        public function ScrollContainer()
        {
            scrollRect = new Rectangle(0, 0, 100, 100);
        }
		
        
		public function set fixedWidth (value:Number):void
		{
            if (scrollRect)
                scrollRect = new Rectangle(scrollRect.x, scrollRect.y, value, scrollRect.height);
            else
                scrollRect = new Rectangle(0, 0, 0, value);
		}
		
        
		public function get fixedWidth():Number
		{
			return scrollRect.width;
		}
		
        
		public function set fixedHeight (value:Number):void
		{
            if (scrollRect)
                scrollRect = new Rectangle(scrollRect.x, scrollRect.y, scrollRect.width, value);
            else
                scrollRect = new Rectangle(0, 0, value, 0);
		}
        
        
        public function get fixedHeight():Number
        {
            return scrollRect.height;
        }
		
		
		override public function addChild(child:DisplayObject):DisplayObject
		{
			measureHeight += child.height;
			if (measureHeight > scrollRect.height)
				dispatchEvent(new Event(Event.CHANGE));
			return super.addChild(child);
		}
		
        
        public function set horizontalPosition(value:Number):void
		{
			_horizontalPosition = value;
			updateMeasureSize();
			var xPos: Number = (measureWidth - scrollRect.width) * value;
			scrollRect = new Rectangle(xPos, scrollRect.y, scrollRect.width, scrollRect.height);
		}
		
		
		public function get horizontalPosition():Number
		{
			return _horizontalPosition;
		}
		
		
		public function set verticalPosition(value:Number):void
		{
			_verticalPosition = value;
			updateMeasureSize();
			var yPos: Number = (measureHeight - scrollRect.height) * value;
			scrollRect = new Rectangle(scrollRect.x, yPos, scrollRect.width, scrollRect.height);
		}
		
		
		public function get verticalPosition():Number
		{
			return _verticalPosition;
		}
		
		public function updateMeasureSize():void
		{
			if (numChildren < 1) return
			var last:DisplayObject = getChildAt(numChildren-1);
			measureWidth =  last.x + last.width;
			measureHeight = last.y + last.height;
		}
	}
}